package com.jkb.trainjieba;

import java.io.IOException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.Mapper.Context;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;


/**
 * 
 * @author wangbin
 * 
 * 功能：计算得出每个类别的总词数
 * 输入：词\t\t\t文章类别\t\t\turl(使用SplitWordsMR产生的数据)
 * 输出：类别\t词数量
 * 运行步骤：第二步
 */
public class TypesWithWordsTotalNumber {

	public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
		//args0:dst
		//args1:out
		//args2:splitMB
		//args3:reduce number
		int SplitMB = Integer.valueOf(args[2]);
		String dst = args[0];
		String out = args[1];
		Configuration conf = new Configuration();
		conf.set("mapreduce.input.fileinputformat.split.maxsize", String.valueOf(SplitMB * 1024 * 1024));
		conf.set("mapred.min.split.size", String.valueOf(SplitMB * 1024 * 1024));
		conf.set("mapreduce.input.fileinputformat.split.minsize.per.node", String.valueOf(SplitMB * 1024 * 1024));
		conf.set("mapreduce.input.fileinputformat.split.minsize.per.rack", String.valueOf(SplitMB * 1024 * 1024));
		conf.set("mapred.job.reuse.jvm.num.tasks", "-1");
		conf.set("mapred.child.java.opts", "-Xmx350m -Xmx1024m");
		Job job = new Job(conf);
		FileInputFormat.addInputPath(job, new Path(dst));
		FileOutputFormat.setOutputPath(job, new Path(out));
		
		job.setMapperClass(CountWordMap.class);
		job.setReducerClass(CountWordReduce.class);
		
		job.setNumReduceTasks(Integer.valueOf(args[3]).intValue());
		
		job.setMapOutputKeyClass(Text.class);
		job.setMapOutputValueClass(LongWritable.class);
		
		job.setOutputKeyClass(Text.class);
		job.setOutputValueClass(LongWritable.class);
		
		job.setJarByClass(TypesWithWordsTotalNumber.class);
        job.waitForCompletion(true);

	}
	
	public static class CountWordMap extends Mapper<Object,Text,Text,LongWritable>{
		
		public final static String SP = "\t\t\t";
		
		@Override
		public void map(Object key,Text value,Context context) throws IOException, InterruptedException{
			String[] line = value.toString().split(SP);
			if(line.length >= 3){
				String type = line[1];
				context.write(new Text(type),new LongWritable(1));
			}
		}
	}
	
	public static class CountWordReduce extends Reducer<Text,LongWritable,Text,LongWritable>{
		@Override
		public void reduce(Text key,Iterable<LongWritable> values,Context context) throws IOException, InterruptedException {
			long sum = 0;
			for(LongWritable v : values){	
				sum += v.get();
			}
			context.write(key,new LongWritable(sum));
		}
		
	}

}
